import json

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from utils.decorators import token_required
from django.views.decorators.http import require_POST
from utils.crypto import DECRYPT
from django.http import JsonResponse
from .models import Menu,MenuItem
from django.db.models import Q
from django.core.paginator import Paginator
from utils.public import build_item_tree

@require_POST
@csrf_exempt
@token_required
def get_main_all_menu(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    if data.get('name'):
        name = data.get('name')
    else:
        name = ''
    try:
        eligible_menus = Menu.objects.filter(
            Q(name__icontains=name) |
            Q(items__title__icontains=name)
        ).distinct()
        result = []
        for menu in eligible_menus:
            top_items = MenuItem.objects.filter(
                menu=menu,
                parent=None,
                is_active=True,
                title__icontains=name  # 仅保留符合条件的顶级子项，若要显示所有可删除此条件
            ).order_by('order')

            # 3. 递归构建子菜单树（如果子项有嵌套层级）
            children = build_item_tree(top_items)

            # 4. 构建Menu数据（即使children为空，也保留当前Menu）
            menu_data = {
                'id': menu.id,
                'name': menu.name,
                'description': menu.description,
                'created_at': menu.created_at.isoformat(),
                'updated_at': menu.updated_at.isoformat(),
                'children': children  # 可能为空列表，但Menu本身会被保留
            }
            result.append(menu_data)
        secret = DECRYPT.encrypt({'status': 'success','data':result, 'message': '获取成功', 'code': 200})
        return JsonResponse({'secret': secret}, status=200)

    except Exception as e:
        import traceback
        traceback.print_exc()
        secret = DECRYPT.encrypt({'status': 'success', 'message': '系统错误', 'code': 200})
        return JsonResponse({'secret': secret}, status=500)


@require_POST
@csrf_exempt
@token_required
def add_main_menu_item(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    parent_id = data.get('parent_id')
    menu_id = data.get('menu_id')
    title = data.get('title')
    target = data.get('target')
    url = data.get('url')
    icon = data.get('icon')
    id = data.get('id')
    if id:
        menu_item = MenuItem.objects.get(id=id)
        for field, value in data.items():
            setattr(menu_item, field, value)
        menu_item.save()
        secret = DECRYPT.encrypt({'status': 'success', 'message': '操作成功', 'code': 200})
        return JsonResponse({'secret': secret}, status=200)
    try:
        menu = Menu.objects.get(id=menu_id)
        if MenuItem.objects.filter(title=title).exists():
            secret = DECRYPT.encrypt({'status': 'error', 'message': '同级菜单中标题不能重复', 'code': 201})
            return JsonResponse({'secret': secret}, status=200)
        parent = None
        if parent_id:
            try:
                parent = MenuItem.objects.get(id=parent_id)
                print(parent,'ddd')
            except MenuItem.DoesNotExist:
                secret = DECRYPT.encrypt({'status': 'error', 'message': '未找到父级id', 'code': 201})
                return JsonResponse({'secret': secret}, status=201)
        MenuItem.objects.create(
            title=title,
            menu=menu,  # 直接关联主菜单对象
            target=target,
            url=url,
            parent=parent,
            icon=icon,
        )
        secret = DECRYPT.encrypt({'status': 'success', 'message': '操作成功', 'code': 200})
        return JsonResponse({'secret': secret}, status=200)
    except Menu.DoesNotExist:
        secret = DECRYPT.encrypt({'status': 'success', 'message': '未找到父级id', 'code': 201})
        return JsonResponse({'secret': secret}, status=201)

@require_POST
@csrf_exempt
@token_required
def add_main_menu(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    id = data.get('id')
    if id:
       menus = Menu.objects.get(id=id)
       for field, value in data.items():
           setattr(menus, field, value)
       menus.save()
       secret = DECRYPT.encrypt({'status': 'success', 'message': '操作成功', 'code': 200})
       return JsonResponse({'secret': secret}, status=200)
    description = data.get('description')
    name = data.get('name')
    if len(name) == 0:
        secret = DECRYPT.encrypt({'status': 'error', 'message': '菜单名称不能为空', 'code': 201})
        return JsonResponse({'secret': secret}, status=200)
    if Menu.objects.filter(name=name).exists():
        secret = DECRYPT.encrypt({'status': 'error', 'message': '菜单名称不能重复', 'code': 201})
        return JsonResponse({'secret': secret}, status=200)
    Menu.objects.create(name=name, description=description)
    secret = DECRYPT.encrypt({'status': 'success', 'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)

@require_POST
@csrf_exempt
@token_required
def get_main_menu(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    if data.get('name'):
        name = data.get('name')
    else:
        name = ''
    pageNum = data.get('pageNum')
    pageSize = data.get('pageSize')
    menus = Menu.objects.filter(
        Q(name__icontains=name)
    ).all().order_by('updated_at')
    paginator = Paginator(menus, pageSize)
    listData = paginator.page(pageNum)
    menu_list = []
    for menu in listData:
        menu_list.append({
            'name': menu.name,
            'id': menu.id,
            'description': menu.description,
            'created_at': menu.created_at.isoformat(),
            'updated_at': menu.updated_at.isoformat(),
        })
    secret = DECRYPT.encrypt({'total':paginator.count,'status': 'success', 'data': menu_list, 'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)

@require_POST
@csrf_exempt
@token_required
def delete_main_menu(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    id = data.get('id')
    menu = Menu.objects.get(id=id)
    if menu.items.exists():
        secret = DECRYPT.encrypt({'status': 'error', 'message': f"当前应用下级存在（{menu.items.count()}条）关联数据，请删除关联数据后在删除！", 'code': 201})
        # secret = DECRYPT.encrypt({'status': 'error', 'message': f"存在子菜单（{menu.items.count()}条）", 'code': 201})
        return JsonResponse({'secret': secret}, status=200)
    menu.delete()
    secret = DECRYPT.encrypt({'status': 'error', 'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)

@require_POST
@csrf_exempt
@token_required
def info_main_menu(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    id = data.get('id')
    menus = Menu.objects.get(id=id)
    data = {
        'id': menus.id,
        'name': menus.name,
        'description': menus.description,
        'created_at': menus.created_at.isoformat(),
    }
    secret = DECRYPT.encrypt({'status': 'error','data': data,'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)

@require_POST
@csrf_exempt
@token_required
def delete_main_menu_children(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    id = data.get('id')
    menus = MenuItem.objects.filter(id=id)
    if len(menus)==0:
        secret = DECRYPT.encrypt({'status': 'error', 'message': '删除失败', 'code': 201})
        return JsonResponse({'secret': secret}, status=201)
    menus.delete()
    secret = DECRYPT.encrypt({'status': 'error', 'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)

@require_POST
@csrf_exempt
@token_required
def info_main_menu_children(request):
    res = json.loads(request.body.decode('utf-8'))['secret']
    data = json.loads(DECRYPT.decrypt(res))
    id = data.get('id')
    menus = MenuItem.objects.get(id=id)
    data = {
        'menu_id': menus.menu_id,
        'id': menus.id,
        'parent_id': menus.parent_id,
        'type': menus.type,
        'target': menus.target,
        'url': menus.url,
        'icon': menus.icon,
        'title': menus.title
    }
    secret = DECRYPT.encrypt({'status': 'error','data': data,'message': '操作成功', 'code': 200})
    return JsonResponse({'secret': secret}, status=200)